/**
 * create by zhike
 * date:2015年3月12日
 */
package com.acooly.module.openapi.client.provider.allinpay.marshall;

import com.acooly.module.openapi.client.api.exception.ApiClientProcessingException;
import com.acooly.module.openapi.client.api.marshal.ApiUnmarshal;
import com.acooly.module.openapi.client.api.message.MessageFactory;
import com.acooly.module.openapi.client.provider.allinpay.OpenAPIClientAllinpayProperties;
import com.acooly.module.openapi.client.provider.allinpay.domain.AllinpayResponse;
import com.acooly.module.openapi.client.provider.allinpay.enums.AllinpayServiceEnum;
import com.acooly.module.openapi.client.provider.allinpay.utils.XmlUtils;
import com.acooly.module.safety.key.KeyLoadManager;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author zhike
 */
@Service
@Slf4j
public class AllinpayResponseUnmarshall extends AllinpayMarshallSupport implements ApiUnmarshal<AllinpayResponse, String> {

    private static final Logger logger = LoggerFactory.getLogger(AllinpayResponseUnmarshall.class);

    @Resource(name = "allinpayMessageFactory")
    private MessageFactory messageFactory;

    @Autowired
    private KeyLoadManager keyStoreLoadManager;

    @Autowired
    private OpenAPIClientAllinpayProperties properties;


    @SuppressWarnings("unchecked")
    @Override
    public AllinpayResponse unmarshal(String message, String serviceName) {
        try {
            logger.info("响应报文:{}", message);
            // 验签
            doVerifySign(message);
            log.info("验签成功");
            return doUnmarshall(message, serviceName);
        } catch (Exception e) {
            throw new ApiClientProcessingException("解析响应报文异常"+e.getMessage());
        }
    }

    protected AllinpayResponse doUnmarshall(String respXml, String serviceName) {
        AllinpayResponse response = (AllinpayResponse) messageFactory.getResponse(AllinpayServiceEnum.find(serviceName).getCode());
        response = XmlUtils.toBean(respXml,response.getClass());
        response.setService(AllinpayServiceEnum.find(serviceName).getCode());
        return response;
    }

    public void setMessageFactory(MessageFactory messageFactory) {
        this.messageFactory = messageFactory;
    }


}
